package com.hmall.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * @version 1.0
 * @date 2024/6/5 17:41
 */
public class UserInfoInterceptor implements HandlerInterceptor {

    /**
     * 目标方法前置处理逻辑：从request中获取user-info请求头，并放入ThreadLocal中
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、从request中获取user-info请求头
        String userId = request.getHeader("user-info");
        // 2、放入ThreadLocal中
        if(ObjectUtil.isNotEmpty(userId)){
            UserContext.setUser(Long.valueOf(userId));
        }
        return true;
    }

    /**
     * 即使目标方法抛异常它也会执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
